/* 微信h5开发使用的相关工具方法 */

import {WxH5, WxOaLoginOptions} from "../../types";

/**
 * @method checkWxBrowser
 * @description 检测是否微信H5浏览器环境
 * @return boolean
 * */
export const checkWxBrowser = () => {
    const ua = navigator.userAgent.toLowerCase();
    const matchs = ua.match(/MicroMessenger/i);
    return !!(matchs && matchs.indexOf('micromessenger') > -1);
}
/**
 * @method getPhoneType
 * @description 获取手机操作系统型号
 * @return string
 * */
export const getPhoneType = () => {
    const ua = navigator.userAgent;
    const android = ua.indexOf('Android') > -1 || ua.indexOf('Linux');
    const ios = !!ua.match(/iPhone|Mac|mac|iPad|ios/i);
    if(android) return 'android';
    if(ios) return 'ios';
    return 'other';
}
/**
 * @method getUrlQueryParam
 * @description url中参数转换获取
 * @param key: string
 * @return param: Object
 * */
export const getUrlQueryParam = (key = '') => {
    const query = decodeURIComponent(window.location.search || window.location.href);
    const queryArr = query.split('?');
    queryArr.shift();
    const queryObj: any = {};
    if(queryArr[0]) {
        const queryParams = queryArr[0].split('&');
        for(let i = 0; i < queryParams.length; i++) {
            if(queryParams[i]) {
                queryObj[queryParams[i].split('=')[0]] = queryParams[i].split('=')[1];
            }
        }
    }
    if(key) return queryObj[key];
    return queryObj;
}
/**
 * @method wxOaLogin
 * @description 微信H5公众号登录方法
 * @param options: WxOaLoginOptions
 * @return void
 * */
export const wxOaLogin = (options: WxOaLoginOptions): void => {
    const appId = options?.appId;
    const redirect_url = options?.redirect_url;
    const scope = options?.scope;
    const state = options?.state;
    const wxLoginUrl = 'https://open.weixin.qq.com/connect/oauth2/authorize';
    // 登录地址
    window.location.href = `${wxLoginUrl}?appid=${appId}&redirect_url=${redirect_url}&response_type=code&scope=${scope}&state=${state}#wechat_redirect`;
}
/**
 * @method getWxCode
 * @description 微信H5公众号发起登录后获取code
 * @param options: WxOaLoginOptions
 * @param callBack: Function
 * @return code
 * */
export const getWxCode = (options: WxOaLoginOptions, callBack: Function) => {
    const wxCode = getUrlQueryParam('code');
    const appId = options?.appId;
    const scope = options?.scope;
    if(!wxCode && appId) {
        const localUrl = window.location.href;
        const redirect_url = encodeURIComponent(localUrl);
        const state = encodeURI(window.location.hash.replace('#', '').split('?')[0]);
        wxOaLogin({
            appId: appId,
            redirect_url: redirect_url,
            state: state,
            scope: scope
        });
    } else {
        callBack && callBack(wxCode);
    }
    return wxCode;
}
/**
 * @method backToWxOaMenu
 * @description 微信公众号H5手动回退到公众号菜单窗口
 * @return void
 * */
export const backToWxOaMenu = () => {
    document.addEventListener('WeixinJSBridgeReady', function () {
        // @ts-ignore
        WeixinJSBridge.call('closeWindow');
    },false);
    // @ts-ignore
    WeixinJSBridge.call('closeWindow');
}
/**
 * @method watchHistoryBackWxOaMenu
 * @description 监听微信公众号H5路由历史回退，回到公众号菜单窗口
 * @return void
 * */
export const watchHistoryBackWxOaMenu = () => {
    window.addEventListener('popstate', function (event: Event) {
        backToWxOaMenu();
    })
}
/**
 * @method disabledWxOaBackHistoryRoute
 * @description 禁用历史路由回退
 * @return void
 * */
export const disabledWxOaBackHistoryRoute = () => {
    history.pushState(null, '', document.URL);
    window.addEventListener('popstate', function (event: Event) {
        history.pushState(null, '', document.URL);
    }, false);
}

// 微信 h5 工具方法集
export const wxH5: WxH5 = {
    checkWxBrowser,
    getPhoneType,
    getUrlQueryParam,
    wxOaLogin,
    getWxCode,
    backToWxOaMenu,
    watchHistoryBackWxOaMenu,
    disabledWxOaBackHistoryRoute
}
